﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint.Utilities;

namespace CodeCounsel.SharePoint2010.DigiD
{
    class InitWebRequest
        : WebRequest<InitWebResponse>
    {
        Uri _returnUrl;

        public InitWebRequest(Uri returnUrl, DigiDSettings settings)
            : base(settings)
        {
            _returnUrl = returnUrl;
        }

        protected override void GetParameters(
            Dictionary<string, string> requestParameters)
        {
            requestParameters[Schema.RequestType] = RequestType.Authenticate;
            requestParameters[Schema.ApplicationUrl] = SPEncode.UrlEncode(_returnUrl.AbsoluteUri);   
            requestParameters[Schema.ApplicationId] = Settings.ApplicationID;
            requestParameters[Schema.SharedSecret] = Settings.SharedSecret;
            requestParameters[Schema.ASelectServer] = Settings.ServerID;
        }

        protected override void ValidateResponse(InitWebResponse response)
        {
            base.ValidateResponse(response);
            if (String.IsNullOrEmpty(response.ASelectUrl))
            {
                throw new DigiDException("Unexpected empty DigiD login URL");
            }
        }

        protected override InitWebResponse CreateResponse(
            Dictionary<string, string> responseParameters)
        {
            return new InitWebResponse(responseParameters);
        }
    }
}
